package com.ly.chatsimple.tcp.task

import com.google.protobuf.ByteString
import com.ly.data.MessageProtobuf
import com.ly.data.MessageProtobuf.TaskProto
import com.ly.nethub.config.NetHubConfig
import com.ly.nethub.netty.HeartbeatFactory
import com.ly.nethub.state.AppStateObserver
import com.ly.nethub.task.BaseTask
import com.ly.nethub.utils.LogUtils

class TcpHeartBeatFactory : HeartbeatFactory, AppStateObserver {
    private var mIsForeground = true

    override fun create(): BaseTask {

        return object : BaseTask(true) {
            override val timeout: Long
                get() = if (mIsForeground) NetHubConfig.FOREGROUND_HEARTBEAT_INTERVAL else NetHubConfig.BACKGROUND_HEARTBEAT_INTERVAL


            override fun buildRequest(): Any {
                return TaskProto.newBuilder()
                    .setFrom("com.ly.chatsimple")
                    .setSeq(taskId)
                    .setType(MessageProtobuf.TaskType.Heartbeat)
                    .setData(ByteString.EMPTY)
                    .setVersion("v1.0")
                    .build()
            }

            override fun isValidResponse(msg: Any?): Any? {
                if (msg == null) return null
                if (msg !is TaskProto) {
                    LogUtils.d("$TAG 不是TaskProto $msg")
                    return null
                }
                if (taskId == msg.seq) return msg
                return null
            }

        }
    }

    override val interruptionTime: Long
        get() = 45 * 1000L

    companion object {
        const val TAG = "HearBeatFactory"
    }

    override fun onBackground() {
        mIsForeground = false
    }

    override fun onForeground() {
        mIsForeground = true
    }
}